package com.controleur.listener.impl;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.JOptionPane;

import com.main.EasyLunch;
import com.modele.dao.impl.RestaurantDAO;
import com.modele.dao.impl.TypeRestaurantDAO;
import com.modele.entity.Restaurant;
import com.modele.entity.TypeRestaurant;
import com.vue.Fenetre;
import com.vue.RestaurantAjoutVue;
import com.vue.RestaurantListeVue;

public class RestaurantAjoutListener implements ActionListener{
	
	public Fenetre fenetre;
	public Restaurant resto;
	
	public RestaurantAjoutListener(Fenetre fenetre){
		this.fenetre=fenetre;
	}

	@Override
	public void actionPerformed(ActionEvent e) {
	   String s = e.getActionCommand();
       if (s.equals("Sauvegarder")) {

    	    this.resto = ajoutRestaurant();
	      	this.fenetre.setPanneau(new RestaurantListeVue(fenetre));
	   }
	}
	public Restaurant ajoutRestaurant(){
		int idType = 0;
		String typeNom=null;
		RestaurantDAO dao = (RestaurantDAO)EasyLunch.getFactory().getRestaurantDAO();
		RestaurantAjoutVue form = (RestaurantAjoutVue)fenetre.getPanneauApplication();

		if (form.getType().getSelectedItem().toString().equals("Nouveau")){
			//ajout d'un nouveau type
			typeNom = JOptionPane.showInputDialog(null, "Entrer un nouveau type : ", "Nouveau", JOptionPane.PLAIN_MESSAGE); 
			if(typeNom!=null){
				TypeRestaurantDAO daoType = (TypeRestaurantDAO)EasyLunch.getFactory().getTypeRestaurantDAO();
				daoType.create(typeNom);
			}
			
			
		}else{
			 typeNom =  form.getType().getSelectedItem().toString();
		}
		//annulation ...
		if(typeNom!=null){
			idType = dao.findIdTypeByName(typeNom);		
			resto = new Restaurant(
					form.getNom().getText(),
					new TypeRestaurant(idType,typeNom), 
					form.getVille().getText(),
					form.getNumero().getText(),
					form.getRue().getText(), 
	      			form.getCp().getText(),
	      			form.getDesc().getText(),
	      			form.getTel().getText(),
	      			form.getSite().getText()
					);
			dao.create(resto);
			return resto;
		}
		return null;
	}
	
}
